package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.RedisConstant;
import com.sky.mapper.user.UserDishFlavorMapper;
import com.sky.mapper.user.UserDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.service.user.UserDishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserDishServiceImpl implements UserDishService {
    @Autowired
    private UserDishMapper userDishMapper;
    @Autowired
    private UserDishFlavorMapper userDishFlavorMapper;
    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        String key = RedisConstant.CATEGORY_CACHE_PREFIX + categoryId;
        String jsonString = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.hasText(jsonString)){
            log.info("从缓存中查询，categoryId：{}",categoryId);
            return JSONObject.parseArray(jsonString,DishVO.class);
        }
        List<Dish> dishList = userDishMapper.queryList(categoryId);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = userDishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishList));
        return dishVOList;
    }
}
